module Prettify(Doc, (<>), fsep, hcat, char, text, empty, compact, pretty) where

import Data.List

data Doc = DocList [String]
           deriving (Eq, Show)

listFromDoc (DocList x) = x
listToDoc x = DocList x

(<>) (DocList []) d = d
(<>) d (DocList []) = d
(<>) (DocList [a]) (DocList (b:bs)) = DocList ((a ++ b) : bs)
(<>) (DocList (a:as)) d = DocList (a : listFromDoc (DocList as <> d))

fsep = listToDoc . concat . (map listFromDoc)

hcat = foldr (<>) empty

char c = text [c]

text "" = empty
text s = DocList [s]

empty = DocList []

compact (DocList strings) = intercalate "\n" strings

pretty n (DocList doc) = fitToLine n doc where
    fitToLine _ [] = ""
    fitToLine _ [s] = s
    fitToLine remainingLength (s:rest)
        | remainingLength >= (length s) + (length (head rest)) + 1 =
            s ++ " " ++ (fitToLine (remainingLength - (length s) - 1) rest)
        | otherwise = s ++ "\n" ++ (fitToLine n rest)
